import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../services/music_player_service.dart';
import '../services/favorites_service.dart';
import '../services/history_service.dart';
import '../services/playlist_management_service.dart';
import '../models/playlist.dart';
import '../models/song.dart';

class MiniPlayerWidget extends StatefulWidget {
  final VoidCallback onTap;

  const MiniPlayerWidget({
    super.key,
    required this.onTap,
  });

  @override
  State<MiniPlayerWidget> createState() => _MiniPlayerWidgetState();
}

class _MiniPlayerWidgetState extends State<MiniPlayerWidget> {
  bool _isFavorite = false;

  @override
  void initState() {
    super.initState();
    _checkFavoriteStatus();
  }

  Future<void> _addToCustomPlaylist() async {
    final playerService = Provider.of<MusicPlayerService>(context, listen: false);
    final Song? currentSong = playerService.currentSong;
    if (currentSong == null) return;

    // 获取已存在的自定义歌单
    final playlists = await PlaylistManagementService.getPlaylists();

    // 若没有歌单，先新建
    Playlist? target;
    if (playlists.isEmpty) {
      final name = await _promptPlaylistName();
      if (name == null || name.trim().isEmpty) return;
      target = await PlaylistManagementService.createPlaylist(name.trim());
    } else {
      target = await _choosePlaylistDialog(playlists);
      if (target == null) return;
    }

    // 添加歌曲到目标歌单
    await PlaylistManagementService.addSongTo(target.id, currentSong);
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('已添加到“${target.name}”')),
      );
    }
  }

  Future<String?> _promptPlaylistName() async {
    final controller = TextEditingController();
    return showDialog<String>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('新建歌单'),
          content: TextField(
            controller: controller,
            autofocus: true,
            decoration: const InputDecoration(hintText: '请输入歌单名称'),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
            FilledButton(onPressed: () => Navigator.pop(context, controller.text), child: const Text('确定')),
          ],
        );
      },
    );
  }

  Future<Playlist?> _choosePlaylistDialog(List<Playlist> playlists) async {
    return showDialog<Playlist>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('选择歌单'),
          content: SizedBox(
            width: 360,
            child: ListView.separated(
              shrinkWrap: true,
              itemCount: playlists.length,
              separatorBuilder: (_, __) => const Divider(height: 1),
              itemBuilder: (context, index) {
                final p = playlists[index];
                return ListTile(
                  title: Text(p.name),
                  subtitle: Text('${p.songs.length} 首'),
                  onTap: () => Navigator.pop(context, p),
                );
              },
            ),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
            TextButton(
              onPressed: () async {
                final name = await _promptPlaylistName();
                if (name != null && name.trim().isNotEmpty) {
                  final created = await PlaylistManagementService.createPlaylist(name.trim());
                  if (context.mounted) Navigator.pop(context, created);
                }
              },
              child: const Text('新建歌单'),
            ),
          ],
        );
      },
    );
  }

  void _checkFavoriteStatus() async {
    final playerService = Provider.of<MusicPlayerService>(context, listen: false);
    final currentSong = playerService.currentSong;
    if (currentSong != null) {
      final isFavorite = await FavoritesService.isFavorite(currentSong);
      if (mounted) {
        setState(() {
          _isFavorite = isFavorite;
        });
      }
    }
  }

  void _toggleFavorite() async {
    final playerService = Provider.of<MusicPlayerService>(context, listen: false);
    final currentSong = playerService.currentSong;
    if (currentSong != null) {
      if (_isFavorite) {
        await FavoritesService.removeFromFavorites(currentSong);
      } else {
        await FavoritesService.addToFavorites(currentSong);
        // 同时添加到历史记录
        await HistoryService.addToHistory(currentSong);
      }
      setState(() {
        _isFavorite = !_isFavorite;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MusicPlayerService>(
      builder: (context, playerService, child) {
        final currentSong = playerService.currentSong;
        if (currentSong == null) return const SizedBox.shrink();
        
        // 当歌曲变化时，重新检查收藏状态
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _checkFavoriteStatus();
        });

        return GestureDetector(
          onTap: widget.onTap,
          child: Container(
            height: 72,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  const Color(0xFFF8F9FA),
                  const Color(0xFFE9ECEF),
                ],
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 8,
                  offset: const Offset(0, -2),
                ),
              ],
            ),
            child: Column(
              children: [
                // 进度条
                LinearProgressIndicator(
                  value: playerService.progress,
                  backgroundColor: Theme.of(context).colorScheme.surfaceVariant,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    Theme.of(context).colorScheme.primary,
                  ),
                ),
                
                // 播放器内容
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Row(
                      children: [
                        // 专辑封面
                        ClipRRect(
                          borderRadius: BorderRadius.circular(6),
                          child: SizedBox(
                            width: 48,
                            height: 48,
                            child: currentSong.albumImageUrl != null
                                ? CachedNetworkImage(
                                    imageUrl: currentSong.albumImageUrl!,
                                    fit: BoxFit.cover,
                                    placeholder: (context, url) => Container(
                                      color: Theme.of(context).colorScheme.surfaceVariant,
                                      child: const Icon(Icons.music_note, size: 24),
                                    ),
                                    errorWidget: (context, url, error) => Container(
                                      color: Theme.of(context).colorScheme.surfaceVariant,
                                      child: const Icon(Icons.music_note, size: 24),
                                    ),
                                  )
                                : Container(
                                    color: Theme.of(context).colorScheme.surfaceVariant,
                                    child: const Icon(Icons.music_note, size: 24),
                                  ),
                          ),
                        ),
                        
                        const SizedBox(width: 12),
                        
                        // 歌曲信息
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                currentSong.name,
                                style: const TextStyle(
                                  fontWeight: FontWeight.w500,
                                  fontSize: 14,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              Text(
                                currentSong.artistsString,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ],
                          ),
                        ),
                        
                        // 播放控制按钮
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            // 收藏按钮
                            IconButton(
                              onPressed: _toggleFavorite,
                              icon: Icon(
                                _isFavorite ? Icons.favorite : Icons.favorite_border,
                                color: _isFavorite ? Colors.red : null,
                              ),
                              iconSize: 22,
                            ),
                            
                            // 上一首
                            IconButton(
                              onPressed: playerService.hasPrevious ? playerService.previous : null,
                              icon: const Icon(Icons.skip_previous),
                              iconSize: 24,
                            ),
                            
                            // 播放/暂停
                            IconButton(
                              onPressed: playerService.togglePlayPause,
                              icon: Icon(
                                playerService.isPlaying
                                    ? Icons.pause
                                    : playerService.isLoading
                                        ? Icons.hourglass_empty
                                        : Icons.play_arrow,
                              ),
                              iconSize: 28,
                            ),
                            
                            // 下一首
                            IconButton(
                              onPressed: playerService.hasNext ? playerService.next : null,
                              icon: const Icon(Icons.skip_next),
                              iconSize: 24,
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}